﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using NetTaste;
using Product.API.ISerivces.Upload;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Product.API.Serivces.Upload
{
    /// <summary>
    /// 图片服务实现类
    /// </summary>
    public class UploadSerivces : IUploadSerivces
    {
        private readonly string? _accessKey;
        private readonly string? _secretKey;
        private readonly string? _bucket;
        private readonly string? _domain;

        /// <summary>
        /// 获取七牛云配置
        /// </summary>
        /// <param name="configuration">配置信息</param>
        public UploadSerivces(IConfiguration configuration)
        {
            // 从配置读取七牛云参数（提前验证避免空值）
            _accessKey = configuration["Qiniu:AccessKey"];
            _secretKey = configuration["Qiniu:SecretKey"];
            _bucket = configuration["Qiniu:Bucket"];
            _domain = configuration["Qiniu:Domain"];
        }


        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file">图片地址</param>
        /// <returns>返回链接</returns>
        public string UploadFile(IFormFile file, string customFolder)
        {

            if (file == null || file.Length == 0)
            {
                throw new ArgumentException("文件不能为空");
            }

            // 获取文件扩展名并生成唯一文件名，避免文件名冲突
            string fileExtension = Path.GetExtension(file.FileName);
            string fileName = $"{Guid.NewGuid():N}{fileExtension}";
            // 构建七牛云存储路径
            string saveKey = Path.Combine(customFolder, fileName);

            // 设置上传策略
            var putPolicy = SetPutPolicy();

            // 生成上传Token
            var mac = new Mac(_accessKey, _secretKey);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 设置上传区域
            Config config = SetConfigZone();

            // 数据流上传
            using (var fs = file.OpenReadStream())
            {
                FormUploader fu = new FormUploader(config);
                var result = fu.UploadStream(fs, saveKey, token, null);
                if (result.Code != (int)System.Net.HttpStatusCode.OK)
                {
                    throw new Exception($"文件上传失败，错误信息：{result.Text}");
                }
            }

            var imgUrl = _domain + saveKey;

            return imgUrl;
        }

        /// <summary>
        /// 设置上传策略
        /// </summary>
        /// <returns></returns>
        public PutPolicy SetPutPolicy()
        {
            PutPolicy putPolicy = new PutPolicy();

            // 设置要上传的目标空间
            putPolicy.Scope = _bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略有效期(对应于生成的凭证的有效期，单位:秒)
            putPolicy.SetExpires(3600);

            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            return putPolicy;
        }

        /// <summary>
        /// 设置上传区域
        /// </summary>
        /// <returns></returns>
        public Config SetConfigZone()
        {
            Config config = new Config();

            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_North;

            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            return config;
        }

        /// <summary>
        /// 文件删除
        /// </summary>
        /// <param name="url">文件地址</param>
        /// <returns>返回结果</returns>
        public int DeleteFile(string url)
        {
            string key = url.Replace(_domain, "");
            //设置上传区域
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_North;//ZONE_CN_North
            Mac mac = new Mac(_accessKey, _secretKey);

            BucketManager bucketManager = new BucketManager(mac, config);
            HttpResult deleteRet = bucketManager.Delete(_bucket, key);
            if (deleteRet.Code == (int)HttpCode.OK)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }


    }
}
